<template>
  <div class="wrapper studyPageClass">
    <div class="container">
      <div class="title_box">
        <span class="title">{{subjectInfo.clockName}}</span>
        <div class="right">
          <div class="page">{{activeQuestionIndex + 1}}/{{subjectInfo.bmOnlineClockContents.length}}</div>
          <div class="coin">
            <span class="coin_number">{{babyInfo.chuckCurrency}}</span>
          </div>
        </div>
      </div>

      <!-- 视频课 -->
      <div class="video_box" v-if="subjectInfo.remark == 'video'">
        <video id='video' x5-video-player-type="h5-page" webkit-playsinline="true" playsinline="true" @canplay="audioLoad"  @ended="audioEnd" ref="audio" preload="metadata" autoplay="autoplay" controls :src="`${activeQuestion.contentAudioUrl}`" ></video>
      </div>

      <!-- 音频图片课 -->
      <div class="banner" v-else>
        <img :src="`${activeQuestion.contentImageUrl}`" alt="">
        <div class="audio_box">
          <audio id='audio' @canplay="audioLoad"  @ended="audioEnd" ref="audio" preload="metadata" autoplay="autoplay" controls :src="`${activeQuestion.contentAudioUrl}`" ></audio>
        </div>
      </div>

      <div class="btn_box">
        <div clickVoice="true" class="btn_prev" @click="prevQues" v-if="subjectInfo.bmOnlineClockContents.length > 1"></div>
        <div clickVoice="true" class="btn_reset" @click="resetAudio"></div>
        <div clickVoice="true" class="btn_play" @click="playAudio" v-if="!audioPlay"></div>
        <div clickVoice="true" class="btn_pause" @click="pauseAudio" v-else></div>
        <div clickVoice="true" class="btn_next" @click="nextQues" v-if="subjectInfo.bmOnlineClockContents.length > 1"></div>
        <!-- <div class="btn_next" @click="nextQues" v-if="subjectInfo.bmOnlineClockContents.length > 1 && activeQuestion.showNextBtn"></div> -->
      </div>
      <div class="answer_area" v-show="activeQuestion.isInteractive == 1 && activeQuestion.showInteractive">
        <i class="btn_question_voice" @click="playQuesVoice"></i>
        <audio id='audioQues' ref="audioQues"  :src="`${activeQuestion.questionAudioUrl}`" ></audio>
        <div class="answer_box">
          <i class="answer_A" @click="submit('A')">
            <img clickVoice="true" :src="`${activeQuestion.iamgeAUrl}`" alt="">
          </i>
          <i class="answer_B" @click="submit('B')">
            <img clickVoice="true" :src="`${activeQuestion.iamgeBUrl}`" alt="">
          </i>
        </div>
      </div>

    </div>

    <audio id='trueVoice' ref="trueVoice"  src="http://www.mingxiaoclub.cn/zebraOnline/voice/answer_true.mp3" ></audio>
    <audio id='falseVoice' ref="falseVoice"  src="http://www.mingxiaoclub.cn/zebraOnline/voice/answer_false.mp3" ></audio>
    <audio id='completeVoice' ref="completeVoice"  src="http://www.mingxiaoclub.cn/zebraOnline/voice/complete.mp3" ></audio>

    <van-popup v-model="showPop" round>
      <div class="pop_box" >
        <div class="answer_right answer" @click="showPop = false;" v-show="answer && !complete">
          <img src="../assets/img/answer_right.png" alt="">
        </div>
        <div class="answer_error answer" @click="showPop = false" v-show="!answer && !complete">
          <img src="../assets/img/answer_error.png" alt="">
        </div>
        <div class="complete answer" @click="showPop = false" v-show="complete">
          <div class="chuck_box" v-if="showChuckAni">
            <span>+{{addChuckNum}}</span>
            <div>
              <i class="icon_chuck"></i>
              <i 
                v-for="(item, index) in addChuckNum" 
                :key="index" 
                class="fly_chuck" 
                :class="[chuckAni, aniClass(index)]"></i>
            </div>
          </div>
          <img src="../assets/img/complete.png" alt="">
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style>
.studyPageClass .van-popup{
  background-color: transparent;
}
</style>
<style scoped>
.wrapper {
  /* margin-bottom: 1.333333rem; */
}
.container {
  position: relative;
  height: 100%;
  /* margin-bottom: 2.333333rem; */
}
.title_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: .4rem 0 .4rem .3rem;
}
.title_box .right {
  display: flex;
  align-items: center;
}
.title_box .title, .title_box .page {
  color: #FE8697;
  font-size: .426667rem;
  font-weight: bold;
}
.title_box .title:before {
  content: '';
  display: inline-block;
  width: 0.626667rem;
  height: 0.386667rem;
  background: url('../assets/img/icon_classTitle.png') 0 0 no-repeat;
  background-size: contain;
}
.title_box .page {
  margin-left: .133333rem;
}
.banner {
  position: relative;
  font-size: 0;
}
.audio_box {
  /* position: absolute; */
  bottom: 0;
  width: 100%;
}
#audio {
  width: 100%;
}
#video{
  /* height: 8rem; */
  /* height: 5.6rem; */
  width: 100%;
}
.banner img {
  width: 100%;
  /* max-height: 8.053333rem; */
}

.btn_box {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: .373333rem 1.013333rem;
}
.btn_box > div {
  margin: 0 .466667rem;
}

.btn_box .btn_prev {
  width: .813333rem;
  height: .826667rem;
  background: url('../assets/img/btn_prev.png') 0 0 no-repeat;
  background-size: contain;
}
.btn_box .btn_reset {
  width: 1.053333rem;
  height: 1.053333rem;
  background: url('../assets/img/btn_reset.png') 0 0 no-repeat;
  background-size: contain;
}
.btn_box .btn_pause {
  width: 1.28rem;
  height: 1.28rem;
  background: url('../assets/img/btn_pause.png') 0 0 no-repeat;
  background-size: contain;
}
.btn_box .btn_play {
  width: 1.28rem;
  height: 1.28rem;
  background: url('../assets/img/btn_play.png') 0 0 no-repeat;
  background-size: contain;
}
.btn_box .btn_next {
  width: .813333rem;
  height: .826667rem;
  background: url('../assets/img/btn_next.png') 0 0 no-repeat;
  background-size: contain;
}

.answer_area {
  /* position: absolute; */
  /* bottom: 1.333333rem; */
  /* left: 0; */
  height: 4.866667rem;
  width: 100%;
  background:linear-gradient(360deg,rgba(255,240,143,1) 0%,rgba(255,226,127,1) 100%);
  box-shadow: 0px -1px 7px 1px rgba(227,227,227,0.5);
  border-radius: .48rem .48rem 0 0;
  display: flex;
  margin-bottom: 1.333333rem;
}

.btn_question_voice {
  display: inline-block;
  width: 1.833333rem;
  height: 1.546667rem;
  background: url('../assets/img/btn_question.png') 0 0 no-repeat;
  background-size: contain;
  position: relative;
  top: .733333rem;
  left: 0;
}
.answer_box {
  display: flex;
  justify-content: center;
  align-items: center;
}
.answer_box .answer_A {
  display: inline-block;
  width: 3.946667rem;
  height: 3.946667rem;
  /* background: url('../assets/img/answer1.png') 0 0 no-repeat; */
  /* background-size: contain; */
  animation: blink 2s infinite ease;
  animation-fill-mode: both;
  display: flex;
  align-items: center;
  justify-content: center;
}
.answer_box .answer_B {
  display: inline-block;
  width: 3.946667rem;
  height: 3.946667rem;
  /* background: url('../assets/img/answer2.png') 0 0 no-repeat; */
  /* background-size: contain; */
  animation: blink 2s infinite ease;
  /* animation-delay: 1s; */
  animation-fill-mode: both;
  display: flex;
  align-items: center;
  justify-content: center;
}

.answer_box .answer_A img, .answer_box .answer_B img {
  width: 2.946667rem;
  height: 2.946667rem;
  border-radius: 50%;
}

@keyframes blink {
  0% { transform: scale(.9) }
  50% { transform: scale(1.1) }
  100% { transform: scale(.9) }
}

.answer img {
  /* width: 100%; */
  /* border-radius: 50%; */
}

</style>

<script>
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("studyPageClass");

import aplayer from 'vue-aplayer'

import 'video.js/dist/video-js.css'
import { videoPlayer } from 'vue-video-player'



export default {
  name: 'studyPageClass',
  data() {
    return {
      showPop: false,
      answer: true,
      complete: false,
      activeQuestionIndex: 0,
      activeQuestion: {},
      subjectId: '',
      subjectInfo: {},
      audioPlay: true,
      voiceSrc: '',
      userAnswer: '',
      babyInfo: {},
      showChuckAni: false,
      addChuckNum: '',
    }
  },

  watch: {
    showPop(newVal, oldVal) {
      if(!this.showPop) {
        if(this.userAnswer == this.activeQuestion.trueAnswer) {
          this.nextQues();
        }

        if(this.complete) {
          this.$router.replace({
            name: 'myStudy',
          })
        }
      }
    },

    activeQuestionIndex(newVal, oldVal) {
      this.activeQuestion = this.subjectInfo.bmOnlineClockContents[newVal]
      // if(this.subjectInfo.isFinished == '1') {
      //   this.activeQuestion.showNextBtn = true;
      // }else{
      //   this.activeQuestion.showNextBtn = false;
      // }
    }

  
  },

  created() {
    console.log(this.$route)
    this.subjectId = this.$route.params.subjectId
    this.initBabyInfo();

    
  },

  mounted() {
    
    this.audioPlay = true;
    this.playAudio();

    
  },

  methods: {
    ...mapActions([
      "formGet",
      "post"
    ]),

    initBabyInfo() {
      this.formGet({
        API: 'queryStudentByOpenId',
        data: {
          openId: this.$route.params.openId
        }
      }).then(res => {
        console.log(res);
        this.babyInfo = res;
        this.initData();
      }).catch(err => {

      })
    },

    initData(type) {
      this.post({
        API: 'queryAllClockById',
        data: {
          subjectId: this.subjectId,
          studentId: this.babyInfo.studentId,
          subjectPackageId: this.$route.query.subjectPackageId,
        }
      }).then(res => {
        console.log(res)
        this.subjectInfo = res;
        // this.subjectInfo.bmOnlineClockContents.forEach(item => {
        //   item.showNextBtn = false;
        // })

        let sessionQues = JSON.parse(localStorage.getItem(res.clockId))
        console.log(sessionQues);
        if(sessionQues) {
          // console.log('aaa')
          // console.log(sessionQues.index)
          if(sessionQues.index > this.subjectInfo.bmOnlineClockContents.length) {
            this.activeQuestion = this.subjectInfo.bmOnlineClockContents[0]
          }else{
            this.activeQuestion = this.subjectInfo.bmOnlineClockContents[sessionQues.index]
          }
          // console.log(this.activeQuestion)
          this.activeQuestionIndex = sessionQues.index;
        }else{
          this.activeQuestion = this.subjectInfo.bmOnlineClockContents[0]
          // console.log(this.activeQuestion)
        }


        // 通过 id 获取音频图片播放地址
        this.initTotalUrl();
        

        this.activeQuestion.showInteractive = false
        
        // if(this.subjectInfo.isFinished == '1') {
        //   this.activeQuestion.showNextBtn = true;
        // }else{
        //   this.activeQuestion.showNextBtn = false;
        // }

        // console.log(this.subjectInfo)
        // console.log(this.activeQuestion)
      }).catch(err => {

      })
    },

    initImgUrl(vid, paraName) {
      console.log(this.activeQuestion)
      // 获取图片地址
      this.formGet({
        API: 'getImageInfoData',
        data: {
          imageId: vid,
        }
      }).then(res => {
        console.log(res);
        if(res.imageInfo) {
          let url = res.imageInfo.url;
          console.log(this.activeQuestion)
          this.$set(this.activeQuestion, paraName, url)
          this.$forceUpdate();

        }

      });
    },
    initAudioUrl(vid, paraName) {
      // 获取音频地址
      this.formGet({
        API: 'getPlayInfoData',
        data: {
          videoId: vid
        }
      }).then(res => {
        console.log(res);
        if(res.playInfoList) {
          let url = res.playInfoList[0].playURL;
          this.$set(this.activeQuestion, paraName, url)
          this.$forceUpdate();
        }

      })
    },
    

    initTotalUrl() {
      console.log(this.activeQuestion)
      this.initImgUrl(this.activeQuestion.contentImageFile, 'contentImageUrl');
      this.initAudioUrl(this.activeQuestion.contentAudioFile, 'contentAudioUrl');

      if(this.activeQuestion.iamgeAFile) {
        this.initImgUrl(this.activeQuestion.iamgeAFile, 'iamgeAUrl');
      }
      if(this.activeQuestion.iamgeBFile) {
        this.initImgUrl(this.activeQuestion.iamgeBFile, 'iamgeBUrl');
      }
      if(this.activeQuestion.questionAudioFile) {
        this.initAudioUrl(this.activeQuestion.questionAudioFile, 'questionAudioUrl');
      }
    },

    submit(answer) {
      this.userAnswer = answer;
      this.showPop = true;
      let audio = this.$refs.audio;
      audio.pause();
      this.audioPlay = false;

      
      

      // 如果有交互，回答正确后显示下一页按钮
      // if(answer == this.activeQuestion.trueAnswer && this.activeQuestion.isInteractive == 1) {
      //   this.activeQuestion.showNextBtn = true;
      // }

      // 最后一题, 答对后, 提示完成
      console.log(this.activeQuestionIndex)
      if(this.activeQuestionIndex + 1 == this.subjectInfo.bmOnlineClockContents.length) {
        if(answer == this.activeQuestion.trueAnswer) {
          this.studyCompleteVoicePlay();
          this.studyComplete();
        }else{
          this.complete = false;
        }
      }

      if(answer == this.activeQuestion.trueAnswer) {
        if(!this.complete) {
          this.trueVoicePlay();
        }
      }else{
        if(!this.complete) {
          this.falseVoicePlay();
        }
      }
    },

    trueVoicePlay() {
      let trueVoice = this.$refs.trueVoice;
      this.answer = true;
      trueVoice.play();
    },
    falseVoicePlay() {
      let falseVoice = this.$refs.falseVoice;
      this.answer = false;
      falseVoice.play();
    },

    studyCompleteVoicePlay() {
      let completeVoice = this.$refs.completeVoice
      this.complete = true;
      completeVoice.play();
    },

    studyComplete() {
      this.post({
        API: 'clockInsert',
        data: {
          studentId: this.babyInfo.studentId,
          subjectPackageClockId: this.$route.query.subjectPackageSubjectId,
        }
      }).then(res => {
        // this.rewardChuck(3); // 学完一课奖励3个
        if(this.subjectInfo.isFinished != 1) {
          this.showChuckAni = true;
          this.addChuckNum = 3;
          this.babyInfo.chuckCurrency = Number(this.babyInfo.chuckCurrency) + 3;
        }
        this.$notify({ type: 'success', message: '学习完成', duration: 1200 });
        // setTimeout(() => {
        //   this.$router.push({
        //     name: 'taskDetail',
        //     params: {
        //       openId: this.$route.params.openId
        //     }
        //   })
        // }, 1500)
      })
    },

    rewardChuck(chuckNum) {
      this.post({
        API: 'chuckInsert',
        data: {
          studentId: this.babyInfo.studentId,
          subjectPackageId: this.$route.query.subjectPackageId,
          subjectId: this.activeQuestion.subjectId,
          subjectContentId: this.activeQuestion.subjectContentId,
          rewardNumber: chuckNum,
        }
      }).then(res => {
        console.log(res);
        if(res != -1) {   // 第一次答题，跳出增加查克币动画
          this.showChuckAni = true;
        }
      })
    },
  

    playQuesVoice() {
      this.pauseAudio();
      let audioQues = this.$refs.audioQues;
      // console.log(audioQues)
      setTimeout(() => {
        audioQues.play();
      })

    },

    quesVoicePause() {
      let audioQues = this.$refs.audioQues;
      audioQues.pause();
    },

    isAndroid(){
      var u = navigator.userAgent;
      if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1){
        return true;
      }
    },

    audioLoad() {
      console.log('aaaaa')
      // setTimeout(() => {
        this.playAudio();
      // })
    },

    audioEnd() {
      console.log('aaaaaaEND')
      // this.activeQuestion.showInteractive = true;
      if(this.activeQuestion.isInteractive == 1) {
        this.$set(this.activeQuestion, 'showInteractive', true)
        this.$forceUpdate();
        
        if(this.activeQuestion.questionAudioFile) {
          this.playQuesVoice();
        }
      }else{
        // 语音播放完后，没有交互，
        // this.$set(this.activeQuestion, 'showNextBtn', true)
        

        // 最后一题播放完毕后，提示完成, 清除localstorage, 跳转到列表页
        if(this.activeQuestionIndex == this.subjectInfo.bmOnlineClockContents.length - 1) {
          console.log('结束了')
          this.showPop = true;
          this.studyComplete();
          this.studyCompleteVoicePlay();


          let obj = {
            subjectId: this.activeQuestion.clockId,
            index: 0
          }

          obj = JSON.stringify(obj);
          localStorage.setItem(this.activeQuestion.clockId, obj);

          // console.log(JSON.parse(localStorage.getItem(this.activeQuestion.clockId)))

          setTimeout(() => {
            console.log('结束')
          }, 1500)
          // setTimeout(() => {
          //   this.$router.replace({
          //     name: 'taskDetail',
          //     params: {
          //       openId: this.$route.params.openId,
          //       packageId: this.$route.params.subjectPackageId,
          //       time: '2020-02-12'
          //     }
          //   }, 1500)
          // })
        }else{
          this.nextQues();
          this.$forceUpdate();
        }
      }
      

    },

    resetAudio() {
      let audio = this.$refs.audio;
      audio.currentTime = 0;
    },
    playAudio() {
      let audio = this.$refs.audio;
      this.audioPlay = true;
      setTimeout(() => {
        audio.play();
      })

      if(this.activeQuestion.questionAudioFile) {
        this.quesVoicePause();
      }
    },
    pauseAudio() {
      let audio = this.$refs.audio;
      this.audioPlay = false;
      audio.pause();
    },

    prevQues() {
      if(this.activeQuestionIndex == 0) {
        return false;
      }
      this.activeQuestionIndex --;
      this.audioPlay = true;
      this.playAudio();
      this.$forceUpdate();

      let obj = {
        subjectId: this.activeQuestion.clockId,
        index: this.activeQuestionIndex
      }

      obj = JSON.stringify(obj);
      localStorage.setItem(this.activeQuestion.clockId, obj);

      setTimeout(() => {
        this.initTotalUrl();
      })
    },
    nextQues() {
      if(this.activeQuestionIndex == this.subjectInfo.bmOnlineClockContents.length - 1) {
        return false;
      }
      this.activeQuestionIndex ++;
      this.playAudio();

      setTimeout(() => {
        audio.play();
      })
      this.$forceUpdate();

      let obj = {
        subjectId: this.activeQuestion.clockId,
        index: this.activeQuestionIndex
      }

      obj = JSON.stringify(obj);
      localStorage.setItem(this.activeQuestion.clockId, obj);

      setTimeout(() => {
        this.initTotalUrl();
      })
    },

    aniClass(index) {
      console.log(index)
      return `fly_chuck${index+1}`
    },

  },

  computed: {
    // activeQuestion() {
    //   if(this.subjectInfo) {
    //     this.subjectInfo.bmOnlineClockContents[this.activeQuestionIndex].showInteractive = false;
    //     this.subjectInfo.bmOnlineClockContents[this.activeQuestionIndex].showNextBtn = false;
    //     return this.subjectInfo.bmOnlineClockContents[this.activeQuestionIndex];
    //   }
    // }
  },

  components: {
    aplayer,
    videoPlayer,
  }
}
</script>

